import json
from urllib import request

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from . import models
from django.core import serializers

"""Usage::
    from django.core import serializers
    json = serializers.serialize("json", some_queryset)
    objects = list(serializers.deserialize("json", json))"""

# Create your views here.

def ajax(request):
    return render(request,'xhr.html',locals())


def get_xhr(request):
    return render(request,'get_xhr.html',locals())


def get_xhr_server(request):
    # name=request.GET.get('name','')
    # if name:
    #     return HttpResponse('欢迎'+name)
    # else:
    #     return HttpResponse('xhr请求已到达')
    if request.method == 'GET':
        username = request.GET.get('username')
        if not username:
            return HttpResponse('用户名不能为空')
        else:
            try:
                models.User.objects.get(username=username)
                return HttpResponse("用户已存在")
            except models.User.DoesNotExist:
                return HttpResponse("ok")
    elif request.method == 'POST':
        print(request.POST.get('csrfmiddlewaretoken'))
        username = request.POST.get('username')
        password = request.POST.get('password')
        if not username or not password:
            return HttpResponse('0')
        else:
            try:
                models.User.objects.get(username=username)
                return HttpResponse("0")
            except models.User.DoesNotExist:
                try:
                    a_user=models.User()
                    a_user.username=username
                    a_user.password=password
                    a_user.nickname=username
                    a_user.save()
                except Exception as e:
                    print(e)
                    return HttpResponse("0")
                return HttpResponse("1")


def post(request):
    if request.method == 'GET':
        return render(request,'post_demo.html',locals())

    elif request.method == 'POST':
        username = request.POST.get('username','')
        password = request.POST.get('password', '')
        # return render(request,'post_demo.html',locals())
        return HttpResponse("POST请求已到达 %s %s"%(username,password))

class UerView:
    def get_user_list(self,request):
        if request.method=='GET':
            return render(request, 'user_list.html')

    def get_user_detail(self,request):
        if request.method=='GET':
            user=models.User.objects.all().values()
            temp=''
            for i in user:
                temp+="%s_%s_%s|"%(i['username'],i['password'],i['nickname'])
            temp=temp.strip("|")
            return HttpResponse(temp)


class Json_data:
    def get_data(self,request):
        if request.method=='GET':
            return render(request, 'json_data.html')


    def send_data(self,request):
        if request.method=='GET':
            import time
            time.sleep(3)
            user_list = list(models.User.objects.all().values())
            # return HttpResponse(json.dumps(user_list,ensure_ascii=False),content_type='application/json')
            return JsonResponse(user_list, safe=False,json_dumps_params={'ensure_ascii':False})


class Cross_domain:
    def get_data(self,request):
        if request.method=='GET':
            return render(request,'cross.html')


    def send_data(self,request):
        if request.method=='GET':
            func=request.GET.get('callback','print')
            return HttpResponse(func+"('i have a dream one day')",content_type='text/javascript')



